/*	agscatalog v1.0 <http://http://agscatalog.codeplex.com/>
    developed by Agostino Cirasa   
    is released under the MIT License <http://www.opensource.org/licenses/mit-license.php> 
*/
(function( $, undefined ) {
    //========================== Top-level vars ==========================
    var versionNumber = "v1.0";
    // jsviews object (=== $.views) Note: JsViews requires jQuery is loaded)
    var jsv = $.views;
    if ( !$ ) {
        // jQuery is not loaded.
        throw "requires jQuery"; // for Beta (at least) we require jQuery
    }
    if( !(jsv )) {
        throw "requires JsRender";
    }    
    $.widget( "fourgzero.fgzagscatalog", {
        options: {
            log:false,
            width:350,
            restServers : []
        },
        _create: function() {
            this.catServiceTemplate = $.templates(
                '{{if type == "MapServer" }}'+
                '<tr class="svcRow">'+
                '<td class="ui-widget-content">{{:name}}</td>'+
                '<td class="ui-widget-content" style="width:.8em"><a href="{{:~baseUrl}}/{{:name}}/MapServer" class="fgz_agscatalog_addSvcBtn{{:~index}}" title="aggiungi">{{:name}}</a></td>'+
                '<td class="ui-widget-content" style="width:.8em"><a href="{{:~baseUrl}}/{{:name}}/MapServer" class="fgz_agscatalog_detailSvcBtn{{:~index}}" target="_blank">Dettagli</a></td>'+
                '</tr>'+
                '{{/if}}'
                );
            this.catFolderTemplate = $.templates(
                '<h3>'+
                '<a href="#">{{:#data}}</a>'+
                '</h3>'+
                '<div>'+
                '<table id="fgz_agscatalog_f_{{:#data}}" border="0" style="width: 100%;"> </table>'+
                '</div>'
                );
            this.label = $("<label for='fgz_agscatalog_restUrl'> ArcGIS Server REST Url:</label>").appendTo(this.element);
            this.url = $("<input type='url' id='fgz_agscatalog_restUrl' name='fgz.agscatalog.restUrl' placeholder='http://<host>/<instance>/rest/services'>")
            .css('width', this.options.width+'px')
            .appendTo(this.element)
            .autocomplete({
                source: this.options.restServers, 
                minLength: 0
            })
            .focus(function () {                
                $(this).autocomplete("search");
            });
            
            this.btn = $("<button id='fgz_agscatalog_restConnectBtn'>Connetti</button>")
            .appendTo(this.element)
            .button({
                icons: {
                    primary: "ui-icon-transferthick-e-w"
                }
            })
            .click($.proxy(this._getAGSCatalog, this));
            
            this.catalog = $("<div id='fgz_agscatalog_catalog'></div>").appendTo(this.element);
            
        },
        _init: function() {
        },
        _setOption: function( key, value ) {
            // In jQuery UI 1.8, you have to manually invoke the _setOption method from the base widget
            $.Widget.prototype._setOption.apply( this, arguments );
        },
        _destroy: function() {
            // In jQuery UI 1.8, you must invoke the destroy method from the base widget
            $.Widget.prototype.destroy.call( this );
        },
        log: function(msg) {
            if(!this.options.log) return;
            if(window.console && console.log) { // firebug logger
                console.log(msg);
            }
        },        
        //catalog        
        _getAGSCatalog: function () {
            var self = this; 
            var url = this.url.val(); 
            this.log(url);
            this.catalog.accordion('destroy');
            this.catalog.empty();
            $.getJSON(url + "?f=json&callback=?", function (data) {
                if (data.services.length > 0) {
                    self._renderAGSFolder(data, url, "Services", "root");
                }
                $.each(data.folders, function (index, folder) {
                    self._getAGSFolder(url, folder, index);
                });
            });
        },
        _getAGSFolder: function (url, folder, index) {
            var self = this; 
            $.getJSON(url + "/" + folder + "?f=json&callback=?", function (data) {
                if ("services" in data && data.services.length > 0) {
                    self._renderAGSFolder(data, url, folder, index);
                }
            });
        },
        _renderAGSFolder: function (data, url, folder, index) {
            this.catalog.append(this.catFolderTemplate.render(folder));    
            $("#fgz_agscatalog_f_" + folder).html(this.catServiceTemplate.render(data.services, {
                baseUrl: url, 
                index: "" + index
            }));
            $(".fgz_agscatalog_addSvcBtn" + index).button({
                text: false,
                icons: {
                    primary: 'ui-icon-plusthick'
                }
            }).click($.proxy(this._addSvcClick, this));
            $(".fgz_agscatalog_detailSvcBtn" + index).button({
                text: false,
                icons: {
                    primary: 'ui-icon-newwin'
                }
            });
            this.catalog.accordion('destroy').accordion({
                fillSpace: true
            });
            this.catalog.accordion('resize');
        },
        _addSvcClick : function(event){
            event.preventDefault();
            var anchor = event.currentTarget;
            this._trigger('add', 0, {
                url:anchor.href, 
                text:anchor.innerText
            });
        }

    });

}( jQuery ) );